/**
 * 微应用主题切换测试工具
 * 用于验证主题切换时微应用是否正确显示
 */

// 测试主题切换函数
export function testThemeSwitch() {
  console.log('🧪 开始测试主题切换功能...');
  
  // 获取主题切换按钮
  const themeToggle = document.querySelector('.theme-toggle, .switch-dark, [data-theme-toggle]');
  if (!themeToggle) {
    console.warn('❌ 未找到主题切换按钮');
    return;
  }
  
  console.log('✅ 找到主题切换按钮:', themeToggle);
  
  // 监听微应用状态
  let microAppVisible = false;
  const checkMicroApp = () => {
    const microContainer = document.getElementById('micro-container');
    const microApp = document.querySelector('[data-qiankun]');
    
    console.log('🔍 检查微应用状态:', {
      microContainer: !!microContainer,
      microContainerDisplay: microContainer?.style.display,
      microContainerVisibility: microContainer?.style.visibility,
      microApp: !!microApp,
      microAppTag: microApp?.tagName,
      microAppStyle: microApp?.getAttribute('style')
    });
    
    if (microContainer && microApp) {
      const rect = microContainer.getBoundingClientRect();
      microAppVisible = rect.width > 0 && rect.height > 0;
      console.log('📏 微应用容器尺寸:', { width: rect.width, height: rect.height, visible: microAppVisible });
    }
    
    return microAppVisible;
  };
  
  // 初始状态检查
  console.log('📋 初始状态检查:');
  checkMicroApp();
  
  // 模拟主题切换
  console.log('🔄 模拟主题切换...');
  themeToggle.click();
  
  // 延迟检查
  setTimeout(() => {
    console.log('⏱️ 主题切换后500ms检查:');
    const visible1 = checkMicroApp();
    
    // 再次切换
    setTimeout(() => {
      console.log('🔄 再次切换主题...');
      themeToggle.click();
      
      setTimeout(() => {
        console.log('⏱️ 第二次主题切换后500ms检查:');
        const visible2 = checkMicroApp();
        
        // 总结测试结果
        console.log('📊 测试结果总结:');
        console.log(`- 初始状态: ${microAppVisible ? '可见' : '不可见'}`);
        console.log(`- 第一次切换后: ${visible1 ? '可见' : '不可见'}`);
        console.log(`- 第二次切换后: ${visible2 ? '可见' : '不可见'}`);
        
        if (visible1 && visible2) {
          console.log('✅ 主题切换测试通过 - 微应用始终可见');
        } else {
          console.log('❌ 主题切换测试失败 - 微应用显示异常');
        }
        
      }, 500);
    }, 1000);
  }, 500);
}

// 监听微应用重新挂载事件
export function monitorMicroAppRemount() {
  console.log('👂 开始监听微应用重新挂载事件...');
  
  // 监听微应用重新挂载事件
  window.addEventListener('micro-app-remount', (event: any) => {
    console.log('🎯 接收到微应用重新挂载事件:', event.detail);
    
    // 重新同步主题
    if (typeof (window as any).syncMicroAppTheme === 'function') {
      console.log('[themeTest] 重新同步主题');
      (window as any).syncMicroAppTheme();
    }
    
    // 检查微应用状态
    setTimeout(() => {
      const microContainer = document.getElementById('micro-container');
      const microApp = document.querySelector('[data-qiankun]');
      
      console.log('🔍 重新挂载后检查:', {
        microContainerExists: !!microContainer,
        microAppExists: !!microApp,
        timestamp: new Date().toISOString()
      });
      
      if (microContainer && microApp) {
        const rect = microContainer.getBoundingClientRect();
        console.log(`✅ 微应用重新挂载成功 - 尺寸: ${rect.width}x${rect.height}`);
      } else {
        console.log('❌ 微应用重新挂载失败 - 元素不存在');
      }
    }, 300);
  });
  
  // 监听主题变化事件
  window.addEventListener('theme-changed', (event: any) => {
    console.log('🎨 接收到主题变化事件:', event.detail);
  });
  
  console.log('✅ 事件监听器已设置');
}

// 检查微应用生命周期
export function checkMicroAppLifecycle() {
  console.log('🔍 检查微应用生命周期状态...');
  
  // 检查qiankun相关对象
  const qiankunInfo = {
    poweredByQiankun: window.__POWERED_BY_QIANKUN__,
    qiankunStarted: (window as any).qiankunStarted,
    qiankun: (window as any).qiankun
  };
  
  console.log('🏗️ Qiankun状态:', qiankunInfo);
  
  // 检查全局状态
  if (window.$getGlobalState) {
    try {
      const globalState = window.$getGlobalState();
      console.log('🌍 全局状态:', globalState);
    } catch (error) {
      console.warn('❌ 获取全局状态失败:', error);
    }
  }
  
  // 检查消息服务
  if (window.$messageService) {
    console.log('📨 消息服务可用:', window.$messageService);
  }
  
  // 检查微应用容器
  const containers = ['#micro-container', '#system-app', '[data-qiankun]'];
  containers.forEach(selector => {
    const element = document.querySelector(selector);
    console.log(`📦 容器 ${selector}:`, {
      exists: !!element,
      display: (element as HTMLElement)?.style?.display,
      visibility: (element as HTMLElement)?.style?.visibility,
      className: element?.className
    });
  });
}

// 自动运行测试（如果在浏览器环境中）
if (typeof window !== 'undefined') {
  // 延迟执行，确保页面加载完成
  setTimeout(() => {
    console.log('🚀 微应用主题切换测试工具已加载');
    console.log('💡 可用函数:');
    console.log('  - testThemeSwitch(): 测试主题切换功能');
    console.log('  - monitorMicroAppRemount(): 监听微应用重新挂载事件');
    console.log('  - checkMicroAppLifecycle(): 检查微应用生命周期状态');
    
    // 自动开始监听
    monitorMicroAppRemount();
    checkMicroAppLifecycle();
  }, 2000);
}